package com.bankcomm.luafuction;

import java.io.IOException;

import org.keplerproject.luajava.LuaException;
import org.keplerproject.luajava.LuaState;

import android.R.integer;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnDismissListener;
import android.content.res.AssetFileDescriptor;
import android.content.res.AssetManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnPreparedListener;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

import com.bankcomm.R;
import com.bankcomm.common.ConfigManager;
import com.rytong.tools.ui.Component;
import com.rytong.tools.utils.Utils;

public class LuaVideo implements OnPreparedListener, SurfaceHolder.Callback {

    private static final String TAG = "LuaVideo";
    private Dialog dialog_;
    private SurfaceView surfaceView_;
    private SurfaceHolder holder_;
    private MediaPlayer mediaPlayer_;
    private AssetFileDescriptor afd_;

    public LuaVideo() {
        try {
            Component.LUASTATE.pushObjectValue(this);
            Component.LUASTATE.setGlobal("luavideo");
            final String luahead = "video = {}; ";
            final String load = "function video:load(filename) local a1 = luavideo:load(filename); return a1; end;";
            final String play = "function video:play(mediaPlayer) luavideo:play(mediaPlayer); end;";
            final String stop = "function video:stop(mediaPlayer) luavideo:stop(mediaPlayer); end;";
            final String pause = "function video:pause(mediaPlayer) luavideo:pause(mediaPlayer); end;";
            final String dispose = "function video:dispose(mediaPlayer) luavideo:dispose(mediaPlayer); end;";
            Component.LUASTATE.gc(LuaState.LUA_GCCOLLECT, 0);
            Component.LUASTATE.LdoString(luahead.concat(load).concat(play).concat(stop).concat(pause).concat(dispose));
        } catch (LuaException e) {
            Utils.printException(e);
        }
    }

    /**
     * 加载视频文件
     * 
     * @param filename
     *            文件名称，如果以“/”开头则连接后台服务器下载，否则全部都在本地包内查找具有相同名称的文件。
     * @return 视频文件对象（发生错误则返回nil）
     */
    public Object load(Object filename) {
        if (filename instanceof String) {
            AssetManager assets = ConfigManager.currentView_.getAssets();
            String name = String.valueOf(filename);
            surfaceView_ = new SurfaceView(ConfigManager.currentView_);
            holder_ = surfaceView_.getHolder();
            holder_.setFixedSize(200, 200);
            holder_.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
            holder_.addCallback(this);
            dialog_ = new Dialog(ConfigManager.currentView_, R.style.Dialog_Fullscreen);
            dialog_.setContentView(surfaceView_);
            dialog_.setOnDismissListener(new OnDismissListener() {

                @Override
                public void onDismiss(DialogInterface dialog) {
                    if (mediaPlayer_ != null) {
                        mediaPlayer_.release();
                    }
                }
            });
            try {
                if (name.startsWith("/")) {

                } else {
                    String[] list = assets.list("video");
                    String str = "";
                    int size = list.length;
                    for (int i = 0; i < size; i++) {
                        str = list[i];
                        if (str.equals(name)) {
                            mediaPlayer_ = new MediaPlayer();
                            afd_ = assets.openFd("video/" + name);
                            mediaPlayer_.setDataSource(afd_.getFileDescriptor(), afd_.getStartOffset(),
                                    afd_.getLength());
                            afd_.close();
                            afd_ = null;
                            mediaPlayer_.setOnPreparedListener(LuaVideo.this);
                            return mediaPlayer_;
                        }
                    }
                }
            } catch (IOException e) {
                Utils.printException(e);
            }
        }
        return mediaPlayer_;
    }

    /**
     * @param handle
     *            视频文件对象
     */
    public void play(Object handle) {
        if (handle instanceof MediaPlayer) {
            mediaPlayer_ = (MediaPlayer) handle;
            dialog_.show();
        }
    }

    /**
     * @param handle
     *            视频文件对象
     */
    public void stop(Object handle) {
        if (handle instanceof MediaPlayer) {
            MediaPlayer player = (MediaPlayer) handle;
            player.stop();
            if (dialog_ != null && dialog_.isShowing()) {
                dialog_.dismiss();
            }
        }
    }

    public void resume(Object handle) {
        if (handle instanceof MediaPlayer) {
            MediaPlayer player = (MediaPlayer) handle;
            player.start();
        }
    }

    /**
     * @param handle
     *            视频文件对象
     */
    public void pause(Object handle) {
        if (handle instanceof MediaPlayer) {
            MediaPlayer player = (MediaPlayer) handle;
            player.pause();
        }
    }

    /**
     * @param handle
     *            视频文件对象
     */
    public void dispose(Object handle) {
        if (handle instanceof MediaPlayer) {
            MediaPlayer player = (MediaPlayer) handle;
            player.release();
        }
    }

    @Override
    public void onPrepared(MediaPlayer mp) {
        Log.i(TAG, "onprepared ");
        mp.start();
    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        Log.i(TAG, "surfaceCreated");
        mediaPlayer_.setDisplay(holder);
        mediaPlayer_.prepareAsync();
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
        Log.i(TAG, "surfaceChanged");
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        Log.i(TAG, "surfaceDestroyed");
    }
}